<style>
    .layui-table-sort[lay-sort=desc] .layui-table-sort-desc {
        border-top-color: #EFAD0F;
    }

    .layui-table-sort[lay-sort=asc] .layui-table-sort-asc {
        border-bottom-color: #EFAD0F;
    }
</style>

<body>
    <div class="layuimini-container layui-anim layui-anim-upbit">
        <div class="layuimini-main">
            <fieldset class="table-search-fieldset">
                <legend>搜索信息</legend>
                <div style="margin: 10px 10px 10px 10px">
                    <form class="layui-form layui-form-pane" action="">
                        <div class="layui-form-item" style="text-align: center;">
                            <div class="layui-inline">
                                <label class="layui-form-label">统计方式</label>
                                <div class="layui-input-inline" style="width:120px;height:38px;">
                                    <select id="groupWay" lay-filter="clsSelects">
                                        <option value=1>按条</option>
                                        <option value=2>按数据库</option>
                                    </select>
                                </div>
                            </div>
                            <div hidden>
                                <input type="text" name="orderBy" id="orderBy" lay-filter="orderBy">
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">数据库</label>
                                <div class="layui-input-inline" style="width:120px;height:38px;">
                                    <select id="dbCode" style="text-align: center;text-align-last: center;width: auto;"
                                        autocomplete="off" class="layui-input" lay-filter="dbCode">
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline" id="publish">
                                <label class="layui-form-label">发表时间</label>
                                <div class="layui-input-inline" style="width:120px;height:38px;">
                                    <input type="text" name="startTime" id="date1" autocomplete="off"
                                        class="layui-input">
                                </div>
                                <label style="float: left;padding-top: 4px;padding-right: 4px;">_&nbsp;&nbsp;</label>
                                <div class="layui-input-inline" style="width:120px;height:38px;">
                                    <input type="text" name="endTime" id="date2" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div id="change">
                                <br>
                            </div>
                            <div class="layui-inline" id="search">
                                <label class="layui-form-label">检索方式</label>
                                <div class="layui-input-inline" style="width:140px;height:38px;">
                                    <select name="searchType" lay-filter="searchSelect">
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline" id="word">
                                <label class="layui-form-label">检索词</label>
                                <div class="layui-input-inline" style="width:140px;height:38px;">
                                    <input type="text" id="keyWord" placeholder="请输入检索词" autocomplete="off"
                                        class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="searchSubmit"
                                    style="margin-left:10px;width:90px;height:38px;border:none;outline:none;border-radius:6px;background-color:#007bff;color:white"><i
                                        class="layui-icon"></i> 搜 索</button>
                                <button type="button" class="layui-btn layui-btn-warm" id="download"
                                    onclick="downloadExcel();"
                                    style="width:90px;border-radius:6px;background-color:#26B99A;">
                                    <i class="layui-icon"></i> 导 出</button>
                            </div>
                        </div>
                    </form>
                </div>
            </fieldset>
            <table class="layui-hide" id="artManage" lay-filter="currentTableFilter"></table>
            <div id="page"></div>
        </div>
    </div>
    <script>

        //开始日期
        var today = new Date();
        var start = layui.laydate.render({
            elem: '#date1',
            calendar: true,
            trigger: 'click',
            max: $("#date2").val(),
            istime: true,
            istoday: true,
            done: function (value, date, endDate) {
                if (value != "") {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date,
                    }
                } else { //清空以后最小值
                    end.config.min = {
                        year: 1970,
                        month: 1,
                        date: 1,
                    }
                }
            }
        });

        //结束日期
        var end = layui.laydate.render({
            elem: '#date2',
            calendar: true,
            trigger: 'click',
            max: $("#date2").val(),
            istime: true,
            istoday: true,
            done: function (value, date) {
                if (value != "") {
                    start.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date,
                    }
                } else { //清空以后最大值
                    start.config.max = {
                        year: today.getFullYear(),
                        month: today.getMonth(),
                        date: today.getDate()
                    }
                }
            }
        });

        //初始化变量
        var keyWord = $("#keyWord").val(),
            groupWay = $("#groupWay").val(),
            beginDate = $("#date1").val(),
            endDate = $("#date2").val(),
            orderBy = $("#orderBy").val(),
            isExport = 0,
            alldbCode = "",

            //按条统计时的表格
            byOne = [
                { align: 'center', title: '序 号', type: 'numbers', width: '10%' },
                { field: 'title', title: '题 名', align: 'center', width: '25%' },
                { field: 'dbsource', title: '来 源 数 据 库', align: 'center', width: '15%' },
                { field: 'author', title: '作 者', align: 'center', width: '15%' },
                { field: 'publishdate', title: '发 表 时 间', align: 'center', width: '15%', sort: true },
                { field: 'browse', title: '浏 览 量', align: 'center', width: '10%' },
                { field: 'download', title: '下 载 量', align: 'center', width: '10%', sort: true }

            ],
            //按数据库统计时的表格
            byDatabase = [
                { align: 'center', title: '序 号', type: 'numbers', width: '20%' },
                { field: 'dbsource', title: '来 源 数 据 库', align: 'center', width: '20%' },
                { field: 'totalRESOURCE', title: '资 源 量', align: 'center', width: '20%', sort: true },
                { field: 'totalBROWSERATE', title: '浏 览 量', align: 'center', width: '20%' },
                { field: 'totalDOWNLOADRATE', title: '下 载 量', align: 'center', width: '20%', sort: true }
            ];

        //初始化配置数据
        $(function () {
            //构造检索下拉框
            var searchSelect = [{ "主题": "主题" }, { "题名": "题名" }, { "作者": "作者" }, { "全文": "全文" }]
            for (var index = 0; index < searchSelect.length; index++) {
                var pros = []
                for (var i in searchSelect[index]) {
                    pros.push(i)
                }
                var theValue = pros[0]
                var opt = document.createElement('option')
                opt.setAttribute('value', theValue)
                opt.innerText = theValue
                document.getElementsByName('searchType')[0].appendChild(opt)
            }

            //拼接数据库下拉框
            var nameList = config.json.db;
            var option = '<option value=0>—全部—</option>';
            for (var i = 0; i < nameList.length; i++) {
                if (nameList[i].isOpen) {
                    option += "<option value='" + nameList[i].dbCode + "'>" + nameList[i].showName + "</option>";//循环获取返回值，并组装成html代码
                    alldbCode += nameList[i].dbCode + ","
                }
            }
            alldbCode = alldbCode.substring(0, alldbCode.length - 1)
            $("#dbCode").html('');
            $("#dbCode").append(option);
            layui.form.render('select', 'dbCode');
        })

        //渲染页面
        layui.form.render();

        //封装 表格渲染方法
        function tableRender(tableBar, initTableParams) {
            layuiEx.tableRender("/adminLog/StandardStatistics", 'artManage', 'page', tableBar,
                initTableParams
            );
        }

        //封装 表格排序渲染方法
        function tableSort(tableBar, initTableParams, orderBy) {
            layuiEx.tableSort("/adminLog/StandardStatistics", 'artManage', 'page', tableBar, orderBy,
                initTableParams
            );
        }

        //页面初始化渲染table
        tableRender(byOne, collectParams())

        layui.form.on('select(clsSelects)', function () {
            var groupWay = $("#groupWay").val();
            if (groupWay == 2) {
                $("#publish").hide();
                $("#search").hide();
                $("#word").hide();
                $("#change").hide();
                $("#date1").val("");
                $("#date2").val("");
            } else {
                $("#publish").show();
                $("#search").show();
                $("#word").show();
                $("#change").show();
                $("#orderBy").val("");
            }
            layui.form.render();
        })

        //收集页面参数
        function collectParams() {
            var res = {},
                searchWay = $("select[name='searchType']").val(),
                keyWord = $("#keyWord").val(),
                beginDate = $("#date1").val(),
                endDate = $("#date2").val(),
                dbCode = $("#dbCode").val(),
                orderBy = $("#orderBy").val();
            //获取选取数据库
            if (dbCode == 0) {
                dbCode = alldbCode;
            }
            res.dbCode = dbCode
            res.searchWay = searchWay
            res.keyWord = keyWord
            res.page = "1"
            res.pageSize = "10"
            res.groupWay = $("#groupWay").val()
            res.beginDate = beginDate
            res.endDate = endDate
            res.orderBy = $("#orderBy").val()
            res.isExport = 0
            return res
        };

        //监听搜索
        layui.form.on('submit(searchSubmit)', function (params) {
            var groupWay = $("#groupWay").val();
            if (groupWay == 1) {
                tableRender(byOne, collectParams())
            } else {
                tableRender(byDatabase, collectParams())
            }
            return false;
        })

        //监听表格排序问题
        layui.table.on('sort(currentTableFilter)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var groupWay = $("#groupWay").val();
            if ("download" == obj.field) {
                $("#orderBy").val("下载频次" + " " + obj.type)//obj.field :当前排序的字段名;obj.type:当前排序类型
            }
            if ("publishdate" == obj.field) {
                $("#orderBy").val("发表时间" + " " + obj.type)//obj.field :当前排序的字段名;obj.type:当前排序类型
            }
            if ("totalDOWNLOADRATE" == obj.field) {
                $("#orderBy").val("SUM(下载频次)" + " " + obj.type)//obj.field :当前排序的字段名;obj.type:当前排序类型
            }
            if ("totalRESOURCE" == obj.field) {
                $("#orderBy").val("count(*)" + " " + obj.type)//obj.field :当前排序的字段名;obj.type:当前排序类型
            }
            // layer.msg('读取中，请稍候...', {icon: 16,time:20*1000});
            var groupWay = $("#groupWay").val();
            if (groupWay == 1) {
                tableSort(byOne, collectParams(), obj)
            } else {
                tableSort(byDatabase, collectParams(), obj)
            }
        });

        //显示loading
        function showloading(t) {
            if (t) {//如果是true则显示loading
                loading = layer.load(1, {
                    shade: [0.5, '#000'], //0.1透明度的白色背景
                    content: '<p style="position: relative;left: -50px;">Excel导出中，请稍候...+ <br> + 注意：当条件包含排序时，下载速度会非常缓慢。</p>',
                    success: function (layerContentStyle) {
                        layerContentStyle.find('.layui-layer-content').css({
                            'padding-top': '50px',
                            'text-align': 'left',
                            'line-height': '30px',
                            'color': '#fff',
                            'width': '300px',
                        })
                    }
                });
            } else {//如果是false则关闭loading
                layer.closeAll('loading');
            }
        }

        //获取当前日期
        function timenow() {
            var timenow = new Date();
            var y = timenow.getFullYear();//年
            var m = timenow.getMonth() + 1;//月
            m = m < 10 ? '0' + m : m;
            var d = timenow.getDate();//日
            d = d < 10 ? ('0' + d) : d;
            var time = y + '-' + m + '-' + d;//字符串拼接成自己想要的时间格式，现在是yyyy/mm/dd格式
            return time;
        }

        function downloadExcel() {
            var tips = '确定导出当前条件下的资源统计吗?' + '<br>' + '注意：导出数目超过10000条时，默认导出前10000条数据。';
            layer.confirm(tips, function (index) {
                layer.close(index)
                showloading(true)
                var res = collectParams();
                var url = config.server + "/adminLog/exportStandardStatistics?isExport=1&dbCode=" + res.dbCode + "&searchWay=" + res.searchWay +
                    "&keyWord=" + res.keyWord + "&groupWay=" + res.groupWay + "&beginDate=" + res.beginDate + "&endDate=" + res.endDate + "&orderBy=" + res.orderBy;
                var xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.responseType = 'blob';
                xhr.onload = function () {
                    if (this.status == 200) {
                        showloading(false)
                        var blob = this.response;
                        var link = document.createElement('a'); // 生成一个a标签。
                        link.href = window.URL.createObjectURL(blob); // href属性指定下载链接
                        link.download = timenow() + "资源统计.xlsx";  // dowload属性指定文件名
                        link.click(); // click()事件触发下载
                    }
                };
                xhr.send();
            });
            return false;
        }
    </script>
</body>